package cn.magictodo.weblog.admin.event.subscriber;

import cn.magictodo.weblog.admin.event.ReadArticleEvent;
import cn.magictodo.weblog.common.domain.mapper.StatisticsArticlePVMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

import static cn.magictodo.weblog.common.enums.RedisPrefixEnum.REDIS_ARTICLE_PV;
import static cn.magictodo.weblog.common.enums.RedisPrefixEnum.REDIS_ARTICLE_RADE_NUM;


/**
 * @author liu
 * @since 2023-11-26 22:29
 *
 * 订阅者
 */
@Component
@Slf4j
public class ReadArticleSubscriber implements ApplicationListener<ReadArticleEvent> {

//    @Autowired
//    private ArticleMapper articleMapper;
    @Autowired
    private StatisticsArticlePVMapper articlePVMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(ReadArticleEvent event) {
        // 在这里处理收到的事件，可以是任何逻辑操作
        Long articleId = event.getArticleId();

        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        log.info("==> threadName: {}", threadName);
        log.info("==> 文章阅读事件消费成功，articleId: {}", articleId);

//        今日时间
        LocalDate currDate = LocalDate.now();
        // 执行文章阅读量 +1  存到redis，避免多次访问带来的写入压力

        String prefix = REDIS_ARTICLE_RADE_NUM.getPrefix() + currDate;
//        使用hash存储当日文章阅读量
        redisTemplate.opsForHash().increment(prefix, articleId.toString(), 1);
        redisTemplate.expire(prefix, 1, TimeUnit.DAYS);


        log.info("==> 文章阅读量 +1 操作成功，articleId: {}", articleId);


        // 当日文章 PV 访问量 +1
        //统计今日访问量
        redisTemplate.opsForValue().increment(REDIS_ARTICLE_PV.getPrefix() + currDate);
//        设置超时时间
        redisTemplate.expire(REDIS_ARTICLE_PV.getPrefix() + currDate, 1, TimeUnit.DAYS);
        log.info("==> 当日文章 PV 访问量 +1 操作成功，date: {}", currDate);
    }
}
